const BASE_URL = "http://192.168.56.1:18080"
// const BASE_URL = "http:/10.202.206.173:18080"
import { showErrorToast, showNoneIconToast } from './toast'
import  {useUserStore} from '@/stores/modules/user.js'

// 全局加载状态管理
let loadingCount = 0;
let isLoading = false;


const requestInterceptor = {
    // 请求拦截器
    invoke: (options) => { 
		// 检查是否需要显示加载动画
		// 默认显示，除非明确设置 showLoading 为 false 或者是特定的后台接口
		const shouldShowLoading = options.showLoading === true && 
			!options.url.includes('/portal/article/add/read_count') &&
			!options.url.includes('/portal/resume/hr_view_record');
		
		if (shouldShowLoading) {
			loadingCount++;
			if (!isLoading) {
				isLoading = true;
			
				uni.showLoading({
					title:"加载中..."
				})
			}
		}
		
        if(!options.url.startsWith('http')) {
			options.url = BASE_URL + options.url
		}
		options.header = {
			...options.header,
			'content-type':'application/json'
		}
		// 统一携带token
		const userStore = useUserStore()
		const {token}  = userStore
		if(userStore.token) {
			options.header.Authorization = token
		}
		console.log("请求的数据",options.data);
    },
	

}

// 添加响应拦截器
const request  = ({
	method='GET',
	url,
	header = {},
	data = {},
	showLoading = true
}) => {
	return new Promise((resolve,reject) => {
		// 判断是否需要隐藏加载动画
		const shouldHideLoading = showLoading === true && 
			!url.includes('/portal/article/add/read_count') &&
			!url.includes('/portal/resume/hr_view_record');
		
		uni.request({
			method,
			url,
			header,
			data,
			success: (response) => {
				// 检查响应格式
				let code, msg, data;
				if (response.data && typeof response.data === 'object' && 'code' in response.data) {
					// 标准格式 {code, msg, data}
					({code, msg, data} = response.data);
				} else {
					// 直接返回数据的情况
					code = 200000;
					msg = 'success';
					data = response.data;
				}
				console.log("返回的响应:", data);
				if(code === 200000) {
					if (shouldHideLoading) {
						loadingCount--;
						if (loadingCount <= 0 && isLoading) {
							isLoading = false;
							loadingCount = 0;
							uni.hideLoading({
								fail: () =>{}
							})
						}
					}
					resolve(data)
				}else {
					if (shouldHideLoading) {
						loadingCount--;
						if (loadingCount <= 0 && isLoading) {
							isLoading = false;
							loadingCount = 0;
							uni.hideLoading({
								fail: () =>{},
								complete: ()=> {
									showNoneIconToast(msg)
								}
							})
						} else {
							showNoneIconToast(msg)
						}
					} else {
						showNoneIconToast(msg)
					}
					
					// 检查登录状态是否过期
					if ([40100, 401001, 401002, 401003].includes(code)) {
						const userStore = useUserStore()
						userStore.logoutAction()
						uni.navigateTo({
							url: '/pages/loginRegister/loginRegister'
						})
					}
					
					reject(new Error(msg))
				}
			},
			fail: (error) => {
				if (shouldHideLoading) {
					loadingCount--;
					if (loadingCount <= 0 && isLoading) {
						isLoading = false;
						loadingCount = 0;
						uni.hideLoading()
					}
				}
                console.log(error);
				showNoneIconToast("请求错误:"+error.errMsg)
				reject(error)
			}
		})
	})
}

uni.addInterceptor('request', requestInterceptor)
uni.addInterceptor('uploadFile', requestInterceptor)


export default request